package converts

import (
	"gitee.com/captials-team/ubdframe/src/domain/dto"
	"gitee.com/captials-team/ubdframe/src/domain/models"
)

func ConvertRoleSimples(roles []*models.RbacRole) []*dto.RbacRoleSimple {
	var list []*dto.RbacRoleSimple
	for _, v := range roles {
		list = append(list, ConvertRoleSimple(v))
	}
	return list
}

func ConvertRoleSimple(r *models.RbacRole) *dto.RbacRoleSimple {
	return &dto.RbacRoleSimple{
		Id: r.Id,

		Domain: r.Domain,
		Name:   r.Name,
		Sort:   r.Sort,

		Status: r.Status,
	}
}

func ConvertPermissionSimple(r *models.RbacPermission) *dto.RbacPermissionSimple {
	return &dto.RbacPermissionSimple{
		Id:     r.Id,
		Name:   r.Name,
		Path:   r.Path,
		Type:   r.Type,
		Icon:   r.Icon,
		Sort:   r.Sort,
		Pid:    r.Pid,
		Status: r.Status,
	}
}

func ConvertPermissionSimples(perms []*models.RbacPermission) []*dto.RbacPermissionSimple {
	var list []*dto.RbacPermissionSimple
	for _, v := range perms {
		list = append(list, ConvertPermissionSimple(v))
	}
	return list
}

// PermissionSimpleToTree 转换为树形结构,存在环的话整个环不会进入树列表
func PermissionSimpleToTree(list []*dto.RbacPermissionSimple) []*dto.RbacPermissionSimple {
	var parents = map[int64]*dto.RbacPermissionSimple{}
	var treeList []*dto.RbacPermissionSimple

	for len(parents) != len(list) {
		q := 0
		for _, v := range list {
			if _, exist := parents[v.Id]; exist {
				continue
			}

			if v.Pid == 0 {
				parents[v.Id] = v
				treeList = append(treeList, v)
				q++
			}
			if _, exist := parents[v.Pid]; exist {
				parents[v.Pid].Children = append(parents[v.Pid].Children, v)
				parents[v.Id] = v
				q++
			}
		}

		//发现环
		if q == 0 {
			break
		}
	}

	return treeList
}
